<template>
  <div class="search-conner">
    <form action="/" class="search">
      <van-search
      v-model="searchText"
      show-action
      placeholder="请输入搜索关键词"
      @search="onSearch"
      @cancel="onCancel"
      @focus="isshow = false"
    />
</form>
    <!-- 搜索结果 -->
    <searchResult v-if="isshow" :q="searchText"/>
    <!-- /搜索结果 -->

    <!-- 联想建议 -->
    <searchsuggution
    v-else-if="searchText"
    :searchText="searchText"
    @search="onSearch"
    />
    <!-- /联想建议 -->

    <!-- 搜索历史 -->
    <searchHistory v-else
    :searchHistories="searchHistories"
    @clear-history="searchHistories = [] "
    @search="onSearch"
    />
    <!-- /搜索历史 -->

  </div>
</template>

<script>
import searchHistory from './components/search-history.vue'
import searchResult from './components/search-result.vue'
import searchsuggution from './components/search-suggestion.vue'
import { setItem, getItem } from '@/uitls/storage'
export default {
  components: {
    searchHistory,
    searchResult,
    searchsuggution
  },
  name: 'searchIdenx',
  data () {
    return {
      searchText: '',
      isshow: false, // 搜索结果的展示
      searchHistories: getItem('search-histories') || [] // 搜索的历史记录数据,初始化的时候取
    }
  },
  methods: {
    onSearch (val) {
      // 更新文本框内容
      this.searchText = val

      // 存搜索历史记录
      // 不要重复数据,最新的在前面
      const index = this.searchHistories.indexOf(val)
      if (index !== -1) {
        this.searchHistories.splice(index, 1)
      }
      this.searchHistories.unshift(val)

      // 渲染搜索结果
      this.isshow = true
    },
    onCancel () {
      this.$router.back()
    }
  },
  watch: {
    searchHistories (val) {
      // 同步到本地储存, 改变的时候存
      setItem('search-histories', val)
    }
  }
}
</script>

<style scoped lang="less">
.search-conner {
  padding-top: 106px;
  .van-search {
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    z-index: 1;
    background-color: blue;
    .van-search__action{
      color: #fff;
    }
  }
}
</style>
